package com.example.utils;

import com.example.config.MyJwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class MyJwtUtils {
    @Autowired
    private MyJwtProperties myJwtProperties;
    // 生成token
    public String createJwt(Map<String, Object>  map) {
        return Jwts.builder()
                .setClaims(map)
                .signWith(SignatureAlgorithm.valueOf(myJwtProperties.getSignalType()), myJwtProperties.getKey())
                .setExpiration(new Date(System.currentTimeMillis() + myJwtProperties.getTime()))
                .compact();
    }

    // 解析token
    public Map<String, Object>  parseJwt(String jwt) {
        Claims body = null;
        try {
            body = Jwts.parser()
                    .setSigningKey(myJwtProperties.getKey())
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            //仅仅打印出异常信息，不返回异常，因为token可能被篡改
            e.printStackTrace();
        }
        return body;
    }
}
